package cn.edu.tju.elm.service;

import cn.edu.tju.elm.model.AiChatMessage;
import cn.edu.tju.elm.repository.AiChatMessageRepository;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.client.RestClientException;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Service
public class AiChatService {

    @Autowired
    private AiChatMessageRepository aiChatMessageRepository;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Value("${doubao.api.key:}")
    private String doubaoApiKey;

    @Value("${doubao.api.url:https://api.volcengine.com/ark/v1/bots}")
    private String doubaoApiUrl;

    @Value("${doubao.api.model:bot-20241225165133-3s6sd8gx}")
    private String doubaoModel;

    // 内存中保存最近的对话上下文，可以后续改为Redis缓存
    private final Map<String, List<AiChatMessage>> conversationContext = new ConcurrentHashMap<>();

    /**
     * 发送消息到AI并获取回复
     */
    public String sendMessageToAi(String userMessage, String sessionId, Long userId) {
        try {
            // 保存用户消息
            saveUserMessage(userMessage, sessionId, userId);

            // 验证API密钥
            if (doubaoApiKey == null || doubaoApiKey.isEmpty() || doubaoApiKey.equals("YOUR_DOUBAO_API_KEY_HERE")) {
                log.error("API密钥未配置");
                throw new RuntimeException("豆包API密钥未配置，请在application.properties中配置doubao.api.key");
            }

            // 构建请求体
            Map<String, Object> requestBody = buildAiRequest(userMessage, sessionId);

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + doubaoApiKey);

            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

            // 调用AI API
            log.info("调用豆包AI API，sessionId: {}", sessionId);
            ResponseEntity<Map> response = restTemplate.exchange(
                    doubaoApiUrl,
                    HttpMethod.POST,
                    requestEntity,
                    Map.class
            );

            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                String aiReply = extractAiReply(response.getBody());
                
                // 保存AI回复
                saveAiMessage(aiReply, sessionId, userId);
                
                return aiReply;
            } else {
                log.error("豆包AI API调用失败，状态码: {}", response.getStatusCode());
                throw new RuntimeException("豆包AI服务调用失败，状态码: " + response.getStatusCode());
            }

        } catch (RestClientException e) {
            log.error("豆包AI API调用失败: {}", e.getMessage());
            throw new RuntimeException("豆包AI服务调用失败: " + e.getMessage());
        } catch (Exception e) {
            log.error("调用豆包AI失败", e);
            throw new RuntimeException("豆包AI服务异常: " + e.getMessage());
        }
    }



    /**
     * 构建AI请求
     */
    private Map<String, Object> buildAiRequest(String userMessage, String sessionId) {
        Map<String, Object> request = new HashMap<>();
        
        // 构建消息列表，包含历史上下文
        List<Map<String, Object>> messages = new ArrayList<>();
        
        // 添加系统消息
        Map<String, Object> systemMsg = new HashMap<>();
        systemMsg.put("role", "system");
        systemMsg.put("content", "你是人工智能助手.");
        messages.add(systemMsg);
        
        // 添加历史消息（最近的10条）
        List<AiChatMessage> history = getRecentConversationHistory(sessionId, 10);
        for (AiChatMessage message : history) {
            Map<String, Object> msg = new HashMap<>();
            msg.put("role", message.getMessageType() == AiChatMessage.MessageType.USER ? "user" : "assistant");
            msg.put("content", message.getMessageContent());
            messages.add(msg);
        }

        // 添加当前用户消息
        Map<String, Object> currentMsg = new HashMap<>();
        currentMsg.put("role", "user");
        currentMsg.put("content", userMessage);
        messages.add(currentMsg);

        request.put("model", doubaoModel);
        request.put("messages", messages);
        
        // 设置参数
        request.put("temperature", 0.7);
        request.put("max_tokens", 1000);
        request.put("stream", false);

        return request;
    }

    /**
     * 提取AI回复
     */
    private String extractAiReply(Map<String, Object> response) {
        try {
            if (response.containsKey("choices")) {
                List<Map<String, Object>> choices = (List<Map<String, Object>>) response.get("choices");
                if (!choices.isEmpty()) {
                    Map<String, Object> choice = choices.get(0);
                    if (choice.containsKey("message")) {
                        Map<String, Object> message = (Map<String, Object>) choice.get("message");
                        return message.getOrDefault("content", "抱歉，我没有理解您的问题").toString();
                    }
                }
            }
            return "抱歉，AI服务暂时无法响应";
        } catch (Exception e) {
            log.error("解析AI回复失败", e);
            return "抱歉，解析AI回复时出现错误";
        }
    }

    /**
     * 保存用户消息
     */
    private void saveUserMessage(String content, String sessionId, Long userId) {
        try {
            AiChatMessage message = AiChatMessage.builder()
                    .userId(userId)
                    .sessionId(sessionId)
                    .messageContent(content)
                    .messageType(AiChatMessage.MessageType.USER)
                    .timestamp(LocalDateTime.now())
                    .build();
            
            aiChatMessageRepository.save(message);
            
            // 更新内存中的上下文
            updateConversationContext(sessionId, message);
            
        } catch (Exception e) {
            log.error("保存用户消息失败", e);
        }
    }

    /**
     * 保存AI回复
     */
    private void saveAiMessage(String content, String sessionId, Long userId) {
        try {
            AiChatMessage message = AiChatMessage.builder()
                    .userId(userId)
                    .sessionId(sessionId)
                    .messageContent(content)
                    .messageType(AiChatMessage.MessageType.AI)
                    .timestamp(LocalDateTime.now())
                    .build();
            
            aiChatMessageRepository.save(message);
            
            // 更新内存中的上下文
            updateConversationContext(sessionId, message);
            
        } catch (Exception e) {
            log.error("保存AI回复失败", e);
        }
    }

    /**
     * 更新对话上下文
     */
    private void updateConversationContext(String sessionId, AiChatMessage message) {
        conversationContext.computeIfAbsent(sessionId, k -> new ArrayList<>()).add(message);
        
        // 保持最近20条消息
        List<AiChatMessage> messages = conversationContext.get(sessionId);
        if (messages.size() > 20) {
            messages.remove(0);
        }
    }

    /**
     * 获取最近的对话历史
     */
    private List<AiChatMessage> getRecentConversationHistory(String sessionId, int limit) {
        List<AiChatMessage> history = conversationContext.get(sessionId);
        if (history == null || history.isEmpty()) {
            // 从数据库加载最近的对话记录
            return aiChatMessageRepository.findByUserIdAndSessionIdOrderByTimestampAsc(
                    0L, sessionId // 这里userId暂时传0，实际需要根据sessionId找到对应的userId
            );
        }
        return history;
    }

    /**
     * 获取用户的对话历史
     */
    public List<AiChatMessage> getChatHistory(Long userId, String sessionId) {
        return aiChatMessageRepository.findByUserIdAndSessionIdOrderByTimestampAsc(userId, sessionId);
    }

    /**
     * 获取用户的所有会话ID
     */
    public List<String> getUserSessions(Long userId) {
        return aiChatMessageRepository.findDistinctSessionIdsByUserId(userId);
    }

    /**
     * 生成新的会话ID
     */
    public String generateSessionId() {
        return "session_" + System.currentTimeMillis() + "_" + UUID.randomUUID().toString().substring(0, 8);
    }
}